/**
 * urls 是目标地址的数组
 * maxNum 是最大并发数
 */
function limitedRequest(urls, maxNum) {
    return new Promise(resolve => {
        const results = []; // 存储所有请求的结果
        let index = 0;  // 下一个请求的索引
        let finishedNum = 0; // 已经完成的请求数量
        if(urls.length === 0) {
            resolve(results);
            return;
        }

        async function request() {
            let i = index; // 当前请求的索引
            index++;
            try {
                const res = await fetch(urls[index]);
                results[i] = res;
            } catch (error) {
                results[i] = error; 
            } finally {
                finishedNum++;
                if(finishedNum >= urls.length) {
                    resolve(results)
                } else if(index < urls.length - 1) {
                    request(); 
                }
            }

        }

        let limitedNum = Math.min(maxNum, urls.length);
        for(let i = 0; i < limitedNum; i++) {
            request();
        }
    })
}

export default limitedRequest;